import 'package:flutter/material.dart';
import 'package:moonmate/services/interaction_service.dart';

/// 自定义按钮组件，提供统一的点击反馈和样式
class MoonButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final bool isLoading;
  final bool disabled;
  final bool fullWidth;
  final Color? backgroundColor;
  final Color? textColor;
  final double borderRadius;
  final double paddingVertical;
  final double paddingHorizontal;
  final TextStyle? textStyle;
  final InteractionType? interactionType;
  final bool showHaptic;
  final Duration minTapInterval;
  final String? uniqueKey;
  final Widget? icon;
  final IconPosition iconPosition;
  final MainAxisSize mainAxisSize;

  const MoonButton({
    super.key,
    required this.text,
    required this.onPressed,
    this.isLoading = false,
    this.disabled = false,
    this.fullWidth = false,
    this.backgroundColor,
    this.textColor,
    this.borderRadius = 8.0,
    this.paddingVertical = 12.0,
    this.paddingHorizontal = 24.0,
    this.textStyle,
    this.interactionType = InteractionType.tap,
    this.showHaptic = true,
    this.minTapInterval = const Duration(milliseconds: 300),
    this.uniqueKey,
    this.icon,
    this.iconPosition = IconPosition.left,
    this.mainAxisSize = MainAxisSize.min,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDisabled = disabled || isLoading;
    
    // 使用按钮文本作为默认的唯一键
    final tapKey = uniqueKey ?? text;
    
    return GestureDetector(
      onTap: isDisabled ? null : () {
        InteractionService().debounceTap(
          tapKey,
          onPressed,
          minDelayMs: minTapInterval.inMilliseconds,
        );
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        width: fullWidth ? double.infinity : null,
        padding: EdgeInsets.symmetric(
          vertical: paddingVertical,
          horizontal: paddingHorizontal,
        ),
        decoration: BoxDecoration(
          color: isDisabled
              ? (backgroundColor ?? theme.primaryColor).withAlpha(153) // 0.6 * 255 = 153
              : (backgroundColor ?? theme.primaryColor),
          borderRadius: BorderRadius.circular(borderRadius),
        ),
        child: Row(
          mainAxisSize: mainAxisSize,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (icon != null && iconPosition == IconPosition.left)
              Padding(
                padding: const EdgeInsets.only(right: 8.0),
                child: icon,
              ),
            isLoading
                ? SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(
                        textColor ?? Colors.white,
                      ),
                    ),
                  )
                : Text(
                    text,
                    style: textStyle ??
                        TextStyle(
                          color: textColor ?? Colors.white,
                          fontWeight: FontWeight.w600,
                          fontSize: 16,
                        ),
                    textAlign: TextAlign.center,
                  ),
            if (icon != null && iconPosition == IconPosition.right)
              Padding(
                padding: const EdgeInsets.only(left: 8.0),
                child: icon,
              ),
          ],
        ),
      ),
    );
  }
}

/// 图标位置枚举
enum IconPosition {
  left,
  right,
}

/// 自定义透明按钮组件，提供轻量级的点击反馈
class MoonTextButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final bool disabled;
  final Color? textColor;
  final double paddingVertical;
  final double paddingHorizontal;
  final TextStyle? textStyle;
  final InteractionType? interactionType;
  final bool showHaptic;
  final Duration minTapInterval;
  final String? uniqueKey;
  final Widget? icon;
  final IconPosition iconPosition;

  const MoonTextButton({
    super.key,
    required this.text,
    required this.onPressed,
    this.disabled = false,
    this.textColor,
    this.paddingVertical = 8.0,
    this.paddingHorizontal = 16.0,
    this.textStyle,
    this.interactionType = InteractionType.tap,
    this.showHaptic = true,
    this.minTapInterval = const Duration(milliseconds: 300),
    this.uniqueKey,
    this.icon,
    this.iconPosition = IconPosition.left,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    // 使用按钮文本作为默认的唯一键
    final tapKey = uniqueKey ?? text;
    
    return GestureDetector(
      onTap: disabled ? null : () {
        InteractionService().debounceTap(
          tapKey,
          onPressed,
          minDelayMs: minTapInterval.inMilliseconds,
        );
      },
      behavior: HitTestBehavior.opaque,
      child: Padding(
        padding: EdgeInsets.symmetric(
          vertical: paddingVertical,
          horizontal: paddingHorizontal,
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (icon != null && iconPosition == IconPosition.left)
              Padding(
                padding: const EdgeInsets.only(right: 6.0),
                child: icon,
              ),
            Text(
              text,
              style: textStyle ??
                  TextStyle(
                    color: disabled
                        ? Colors.grey.shade400
                        : (textColor ?? theme.primaryColor),
                    fontWeight: FontWeight.w500,
                  ),
            ),
            if (icon != null && iconPosition == IconPosition.right)
              Padding(
                padding: const EdgeInsets.only(left: 6.0),
                child: icon,
              ),
          ],
        ),
      ),
    );
  }
}

/// 通用触摸反馈组件，包装任何子组件并提供点击反馈
class TouchableOpacity extends StatelessWidget {
  final Widget child;
  final VoidCallback? onTap;
  final VoidCallback? onLongPress;
  final bool disabled;
  final double activeOpacity;
  final EdgeInsets padding;
  final Duration minTapInterval;
  final String? uniqueKey;
  final bool showHaptic;
  final InteractionType tapInteractionType;
  final InteractionType longPressInteractionType;
  final HitTestBehavior behavior;
  final Function()? onTapDown;
  final Function()? onTapUp;

  const TouchableOpacity({
    super.key,
    required this.child,
    this.onTap,
    this.onLongPress,
    this.disabled = false,
    this.activeOpacity = 0.7,
    this.padding = EdgeInsets.zero,
    this.minTapInterval = const Duration(milliseconds: 300),
    this.uniqueKey,
    this.showHaptic = true,
    this.tapInteractionType = InteractionType.tap,
    this.longPressInteractionType = InteractionType.longPress,
    this.behavior = HitTestBehavior.opaque,
    this.onTapDown,
    this.onTapUp,
  });

  @override
  Widget build(BuildContext context) {
    // 使用组件哈希码作为默认的唯一键
    final tapKey = uniqueKey ?? '${runtimeType.hashCode}';
    
    return GestureDetector(
      onTap: disabled || onTap == null ? null : () {
        InteractionService().debounceTap(
          tapKey,
          () async {
            if (showHaptic) {
              await InteractionService()
                  .provideHapticFeedback(tapInteractionType);
            }
            onTap?.call();
          },
          minDelayMs: minTapInterval.inMilliseconds,
        );
      },
      onLongPress: disabled || onLongPress == null ? null : () async {
        if (showHaptic) {
          await InteractionService()
              .provideHapticFeedback(longPressInteractionType);
        }
        onLongPress?.call();
      },
      onTapDown: disabled ? null : (_) => onTapDown?.call(),
      onTapUp: disabled ? null : (_) => onTapUp?.call(),
      behavior: behavior,
      child: Opacity(
        opacity: disabled ? 0.6 : 1.0,
        child: Padding(
          padding: padding,
          child: child,
        ),
      ),
    );
  }
}

/// 加载状态指示器组件
class LoadingIndicator extends StatelessWidget {
  final String message;
  final double size;
  final Color color;
  final TextStyle? textStyle;
  final bool showText;

  const LoadingIndicator({
    super.key,
    this.message = '加载中...',
    this.size = 24.0,
    this.color = Colors.blue,
    this.textStyle,
    this.showText = true,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: size,
            height: size,
            child: CircularProgressIndicator(
              color: color,
              strokeWidth: 2.5,
            ),
          ),
          if (showText)
            Padding(
              padding: const EdgeInsets.only(top: 12.0),
              child: Text(
                message,
                style: textStyle ??
                    const TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
              ),
            ),
        ],
      ),
    );
  }
}

/// 状态显示组件，用于显示加载中、空状态、错误状态
class StatusView extends StatelessWidget {
  final StatusType type;
  final String message;
  final VoidCallback? onRetry;
  final Widget? customIcon;
  final double iconSize;
  final Color? iconColor;
  final bool showAction;
  final String actionText;

  const StatusView({
    super.key,
    required this.type,
    this.message = '',
    this.onRetry,
    this.customIcon,
    this.iconSize = 64.0,
    this.iconColor,
    this.showAction = true,
    this.actionText = '重试',
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    // 确定显示的图标和颜色
    IconData iconData;
    Color defaultIconColor;
    
    switch (type) {
      case StatusType.loading:
        iconData = Icons.cloud_download;
        defaultIconColor = theme.primaryColor;
        break;
      case StatusType.empty:
        iconData = Icons.inbox;
        defaultIconColor = Colors.grey.shade400;
        break;
      case StatusType.error:
        iconData = Icons.error_outline;
        defaultIconColor = Colors.red.shade500;
        break;
      case StatusType.success:
        iconData = Icons.check_circle;
        defaultIconColor = Colors.green.shade500;
        break;
      case StatusType.warning:
        iconData = Icons.warning_amber_rounded;
        defaultIconColor = Colors.amber.shade500;
        break;
    }
    
    final finalIconColor = iconColor ?? defaultIconColor;
    
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (type == StatusType.loading)
              SizedBox(
                width: iconSize,
                height: iconSize,
                child: CircularProgressIndicator(
                  color: finalIconColor,
                  strokeWidth: 3,
                ),
              )
            else
              (customIcon ??
                  Icon(
                    iconData,
                    size: iconSize,
                    color: finalIconColor,
                  )),
            
            const SizedBox(height: 16),
            
            Text(
              message.isEmpty ? _getDefaultMessage(type) : message,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey.shade600,
                height: 1.5,
              ),
            ),
            
            const SizedBox(height: 24),
            
            if (showAction && (type == StatusType.error || onRetry != null))
              MoonButton(
                text: actionText,
                onPressed: onRetry ?? () {},
                backgroundColor: finalIconColor,
                paddingVertical: 10,
                paddingHorizontal: 20,
              ),
          ],
        ),
      ),
    );
  }
  
  String _getDefaultMessage(StatusType type) {
    switch (type) {
      case StatusType.loading:
        return '数据加载中，请稍候...';
      case StatusType.empty:
        return '暂无数据';
      case StatusType.error:
        return '加载失败，请检查网络连接后重试';
      case StatusType.success:
        return '操作成功';
      case StatusType.warning:
        return '请注意';
    }
  }
}

/// 状态类型枚举
enum StatusType {
  loading,
  empty,
  error,
  success,
  warning,
}

/// 带阴影的卡片组件
class ShadowCard extends StatelessWidget {
  final Widget child;
  final EdgeInsets padding;
  final EdgeInsets margin;
  final double borderRadius;
  final Color? backgroundColor;
  final double elevation;
  final VoidCallback? onTap;
  final bool isLoading;
  
  const ShadowCard({
    super.key,
    required this.child,
    this.padding = const EdgeInsets.all(16),
    this.margin = const EdgeInsets.all(8),
    this.borderRadius = 12,
    this.backgroundColor,
    this.elevation = 2,
    this.onTap,
    this.isLoading = false,
  });
  
  @override
  Widget build(BuildContext context) {
    final card = Container(
      padding: padding,
      margin: margin,
      decoration: BoxDecoration(
        color: backgroundColor ?? Colors.white,
        borderRadius: BorderRadius.circular(borderRadius),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withAlpha(51), // 0.2 * 255 = 51
            spreadRadius: 2,
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: isLoading 
          ? LoadingIndicator(showText: false, size: 20)
          : child,
    );
    
    if (onTap != null) {
      return TouchableOpacity(
        onTap: onTap,
        child: card,
      );
    }
    
    return card;
  }
}